<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Contact extends Controller_Initial_Page {
    
    public function action_index()
    {
       $this->action_pending_requests();
    }
   
    public function action_pending_requests()
    {
       $content_view = View::factory('content');      
       $contact_template_view = View::factory('contact/template'); 
       
       $contact_template_view->set('content', $this->generate_pending_requests());
       $contact_template_view->set('menu_selected', 2);
       $content_view->set('content', $contact_template_view);
              
       $this->template->set('body', $content_view);   
    }
    
    public function action_ajax_pending_requests()
    {
        $content = array('content' => $this->generate_pending_requests()->render());
        $this->response->body(json_encode($content));    
    }
    
    private function generate_pending_requests()
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = $user_model->contact_requests;
        $pending_requests = $contact_model->where('status','=',0)->find_all();
        
        $contact_pending_requests_view = View::factory('contact/pending_requests');
        $contact_pending_requests_view->set('pending_requests',$pending_requests);
        return $contact_pending_requests_view;
        
    }
    
    public function action_ajax_approve_request($id)
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = $user_model->contact_requests;
        $contact_model->where('status','=',0)
                      ->where('id','=',(int)$id)
                      ->find();
        
        if ($contact_model->loaded())
        {
            $contact_model->status = 1;
            $contact_model->save();

            $output = array('success' => true,
                            'message' => 'Yes Yes Yes');

            $this->response->body(json_encode($output));    
        }
        else
        {
            throw new HTTP_Exception_404;
        }
                
    }
    
    public function action_ajax_not_approve_request($id)
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = $user_model->contact_requests;
        $contact_model->where('status','=',0)
                      ->where('id','=',(int)$id)
                      ->find();
        
        if ($contact_model->loaded())
        {
            $contact_model->delete();
            $output = array('success' => true,
                            'message' => 'Yes Yes Yes');

            $this->response->body(json_encode($output));    
        }
        else
        {
            throw new HTTP_Exception_404;
        }
                
    }
    
    public function action_ajax_remove($id)
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = ORM::factory('contact');
        $contact_model->where('id','=',(int)$id)
                      ->where('status', '=', 1)
                      ->and_where_open()
                      ->where('sender_id','=', $user_model->id)
                      ->or_where('recipient_id','=', $user_model->id)
                      ->and_where_close()
                      ->find();
        
        if($contact_model->loaded())
        {
            $contact_model->delete();    
            $output = array('success' => true,
                            'message' => 'Yes Yes Yes');

            $this->response->body(json_encode($output));    
        }
        else
        {
            throw new HTTP_Exception_404;
        }
                      
    }
    
    public function action_all()
    {
       $content_view = View::factory('content');      
       $contact_template_view = View::factory('contact/template'); 
       
       $contact_template_view->set('content', $this->generate_all()->render());
       $contact_template_view->set('menu_selected', 1);
       $content_view->set('content', $contact_template_view);
              
       $this->template->set('body', $content_view);   
    }
    
    public function action_ajax_all()
    {
        $content = array('content' => $this->generate_all()->render());
        $this->response->body(json_encode($content));          
    }
    
    private function generate_all()
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = ORM::factory('contact');
        $contacts = $contact_model->get_contacts($user_model->id);
        
        $contact_all_view = View::factory('contact/all');
        $contact_all_view->set('contacts',$contacts);
        $contact_all_view->set('user_id',$user_model->id);
        return $contact_all_view;
    }
    
    public function action_ajax_send_request($url)
    {
        $my_user_model = Auth::instance()->get_user();
        
        $user_model = ORM::factory('user');
        $user_model->with('user_profile')
                   ->where('url','=',$url)
                   ->find();
        
        $contact_model = ORM::factory('contact');       
        
        $privacy = Privacy::factory($my_user_model ? $my_user_model->id : false,
                                    $user_model->id);
        
        if ($privacy->send_invitation_permission())
        {
            $contact_model->sender_id = $my_user_model->id;
            $contact_model->recipient_id = $user_model->id;
            $contact_model->save();
            
            if($user_model->user_privacy->new_invitation_notification)
            {
                // prepare email message  
                $email_title_message = Kohana::message('email', 'send_invitation_request.title');
                $email_title_message = __($email_title_message, array(
                                ':name' => $my_user_model->user_profile->name));
                $main_config = Kohana::config('main');  

                $email_template_view = View::factory('email/template');
                $email_content_view = View::factory('email/send_invitation_request');
                $email_content_view->set('user',$my_user_model);
                $email_template_view->set('title', $email_title_message);
                $email_template_view->set('content', $email_content_view);
                
                $send_email = Email::factory($email_title_message)
                                            ->message($email_template_view, 'text/html')
                                            ->to($user_model->email)
                                            ->from($main_config->contact_mail, $main_config->contact_name)
                                            ->send();
                         
                 if(!$send_email)
                 {
                      Log::instance()->add(Log::ERROR, 'Information about invitation to contact could not be sent to '.$user_model->email);
                 }
            }
            
             $output = array('success' => true,
                             'message' => 'Yes Yes Yes');

            $this->response->body(json_encode($output));    
        }
        else
        {
            throw new HTTP_Exception_404;
        }
        
    }
    
    public function action_ajax_get_contacts()
    {
        
            $user_model = Auth::instance()->get_user();
            $contact_model = ORM::factory('contact');
            
            //TODO: have to get result order by name + surname, 
            
            
                       
                            
            $contacts = $contact_model->join('user_profiles')->on(DB::expr('CASE `sender_id` WHEN '.$user_model->id.' THEN `recipient_id` else `sender_id` END'),'=','user_profiles.user_id')
                                      ->where('status', '=', 1)
                                      ->and_where_open()
                                      ->where('sender_id','=', $user_model->id)
                                      ->or_where('recipient_id','=', $user_model->id)
                                      ->and_where_close()
                                      ->order_by(DB::expr("CONCAT(`user_profiles`.`name`, ' ', `user_profiles`.`surname`)"), 'ASC')
                                      ->find_all();
            
            //echo View::factory('profiler/stats');
        
        $autosuggest_view = View::factory('autosuggest/user');
        $response = Array();
        
        foreach ($contacts as $contact)
        {
            if ($contact->sender == $user_model->id) 
            {
                $user = $contact->recipient->user_profile;
            }
            else
            {                
                $user = $contact->sender->user_profile;
            }
            
            $autosuggest_view->set('user',$user);    
            
            $response[] = array($user->user_id, $user->name.' '.$user->surname, null, $autosuggest_view->render());
        }

        $this->response->body( json_encode($response));
    }
        
    public function action_ajax_get_toggle()
    {
        $user_model = Auth::instance()->get_user();
        $contact_model = $user_model->contact_requests;
        $pending_requests = $contact_model->where('status','=',0)
                                          ->limit(5)
                                          ->order_by('id','DESC')
                                          ->find_all();
        
        //update user notice table
        foreach($pending_requests as $pending_request)
        {
            $notice_model = $user_model->notice;
            $notice_model->contact_id = $pending_request->id;
            $notice_model->save();
            break;
        }
        
        $contact_toggle_template_view = View::factory('contact/toggle_template');
        $contact_toggle_template_view->set('pending_requests',$pending_requests);
        
        $content = array('content' => $contact_toggle_template_view->render());
        $this->response->body(json_encode($content));
    }
    
    public function action_find()
    {
       $content_view = View::factory('content');      
       $contact_template_view = View::factory('contact/template'); 
       
       $contact_template_view->set('content', $this->generate_find());
       $contact_template_view->set('menu_selected', 3);
       $content_view->set('content', $contact_template_view);
              
       $this->template->set('body', $content_view);   
    }
    
    public function action_ajax_find()
    {        
        $content = array('content' => $this->generate_find()->render());
        $this->response->body(json_encode($content));           
    }
    
    private function generate_find()
    {
        $user_model = Auth::instance()->get_user(); 
        $user_id = (int) $user_model->id;
       
        $contact_model = ORM::factory('contact');
        $user_profiles = $contact_model->get_contacts_proposals($user_id);
        
       // var_dump($user_profiles); die;
        
        $find_view = View::factory('contact/find');
        $find_view->set('user_profiles',$user_profiles);
        
       return $find_view;
    }
    
    public function action_internal_contact_proposals()
    {
        $user_model = Auth::instance()->get_user();
        
        //get contact proposals
        $contact_model = ORM::factory('contact');
        $contact_proposals = $contact_model->get_contacts_proposals($user_model->id,5,1,true);
        
        $contact_proposals_view = View::factory('contact/contact_proposals');
        $contact_proposals_view->set('contact_proposals', $contact_proposals);
        $this->response->body($contact_proposals_view); 
    }
    
    
}